﻿// register namespace
Type.registerNamespace('ise.Controls');

ise.Controls.ShippingMethodOption = function (ctrl, shippingMethod, freightCalculation, freight) {
    this.id = ctrl.id;
    this.ctrl = ctrl;
    this.shippingMethod = shippingMethod;
    this.freightCalculation = freightCalculation;
    this.freight = freight;

    var del = Function.createDelegate(this, this.handleOptionClick);
    $addHandler(this.ctrl, 'click', del);
    this.selectedEventHandler = null;
}
ise.Controls.ShippingMethodOption.registerClass('ise.Controls.ShippingMethodOption');
ise.Controls.ShippingMethodOption.prototype = {

    handleOptionClick: function (option) {
        this.onSelected(option);
    },

    onSelected: function (option) {
        if (option) {
            if (this.selectedEventHandler) {
                this.selectedEventHandler(this);
                //hdenOnpage - hidden field indicator that where in the checkout1.aspx
                //if undefined where in the checkoutshipping.aspx
                if ($getElement('hdenOnpage') != undefined) {
                    this.updateSummary(this);
                }
            }
        }
    },

    getIsChecked: function () {
        if (this.ctrl) {
            return this.ctrl.checked;
        }
        return false;
    },

    onCalculationSummaryComplete: function (summary) {

        if (summary == undefined) return;

        $getElement('subtotal_elem').innerHTML = summary.SubTotal;

        if ($getElement('fr_elem') != undefined)
            $getElement('fr_elem').innerHTML = summary.Freight;
        $getElement('tax_elem').innerHTML = summary.Tax;
        $getElement('total_elem').innerHTML = summary.DueTotal;

        var main = this.id.split('_')[0];
        var loadingRow = $getElement(main + '_LoadingRow');
        if (null != loadingRow) { ise.Utils.hideRow(loadingRow); }

        var container = $getElement(main + '_Content');
        if (null != container) { ise.Utils.showRow(container); }

    },

    updateSummary: function (seloption) {
        var main = this.id.split('_')[0];
        var loadingRow = $getElement(main + '_LoadingRow');

        if (null != loadingRow) {
            ise.Utils.showRow(loadingRow);
        }

        var container = $getElement(main + '_Content');
        if (null != container) {
            ise.Utils.hideRow(container);
        }

        var service = new ActionService();
        var calculationSummary = service.GetShippingCalculation(seloption.shippingMethod, seloption.freightCalculation, Function.createDelegate(this, this.onCalculationSummaryComplete));
    },

    setSelectedEventHandler: function (handler) {
        return this.selectedEventHandler = handler;
    },

    getShippingMethod: function () {
        return this.shippingMethod;
    },

    getFreightCalculation: function () {
        return this.freightCalculation;
    },

    getFreight: function () {
        return this.freight;
    }

}

// Constructor
ise.Controls.ShippingMethodControl = function (id) {
    this.id = id;
    this.ctrl = $getElement(id);
    this.addressControlId = null;
    this.addressControl = null;
    this.shippingMethodID = null;
    this.skipShipping = false;
    this.options = new Array();

    this.currentOption = null;

    this.validationController = new ise.Validators.ValidationController();

    if (this.ctrl) {
        this.hookUpRefreshLink();
    }

    // delegate
    this.refreshClickedEventHandler = null;

    this.shippingOptionsLoadedEventHandlers = new Array();

    this.addressValue = null;
}
ise.Controls.ShippingMethodControl.registerClass('ise.Controls.ShippingMethodControl');
ise.Controls.ShippingMethodControl.prototype = {

    getIsSkipShipping: function () {
        return this.skipShipping;
    },

    setIsSkipShipping: function (skip) {
        this.skipShipping = skip;
    },

    hookUpRefreshLink: function () {
        var link = $getElement(this.id + '_Refresh');

        if (link) {
            link.onclick = Function.createDelegate(this, this.handleRefreshClick);
        }
    },

    handleRefreshClick: function () {
        this.onRefreshClicked();
    },

    onRefreshClicked: function (adressid) {
        var shippingInfoValid = false;

        if (this.refreshClickedEventHandler) {
            shippingInfoValid = this.refreshClickedEventHandler(this);
        }

        if (shippingInfoValid) {
            this.requestShippingMethod(adressid);
        }
    },

    setRefreshClickedEventHandler: function (handler) {
        this.refreshClickedEventHandler = handler;
    },

    clearOptions: function () {
        this.options.length = 0;

        this.setShippingMethod(ise.Constants.EMPTY_STRING);
    },

    getCurrentOption: function () {
        return this.currentOption;
    },

    setCurrentOption: function (option) {

        this.currentOption = option;
        this.setShippingMethod(option.getShippingMethod())
        this.setFreightCalculation(option.getFreightCalculation());
        this.setFreight(option.getFreight());
    },

    registerOption: function (option) {
        this.options[this.options.length] = option;

        if (option.getIsChecked()) {
            this.setCurrentOption(option);
        }

        var del = Function.createDelegate(this, this.handleOptionSelected);
        option.setSelectedEventHandler(del);
    },

    handleOptionSelected: function (option) {
        this.setCurrentOption(option);
    },

    setAddressControlId: function (addressId) {
        this.addressControlId = addressId;

        if (ise.Controls.AddressController) {
            var control = ise.Controls.AddressController.getControl(addressId);
            if (null != control) {
                this.addressControl = control;
                this.requestShippingMethod(true);
            }
            else {
                ise.Controls.AddressController.addObserver(this);
            }
        }
    },

    notify: function (ctrl) {
        if (null != this.addressControlId && ctrl) {
            if (ctrl.id == this.addressControlId) {
                this.addressControl = ctrl;
                this.requestShippingMethod(true);
            }
        }
    },

    setAddressValue: function (value) {
        this.addressValue = value;
    },

    addShippingOptionsLoadedEventHandler: function (handler) {
        this.shippingOptionsLoadedEventHandlers.push(handler);
    },

    onShippingOptionsLoaded: function () {
        for (var ctr = 0; ctr < this.shippingOptionsLoadedEventHandlers.length; ctr++) {
            var handler = this.shippingOptionsLoadedEventHandlers[ctr];
            handler(this);
        }
    },

    onLoadShippingMethodComplete: function (shippingMethods) {
        this.clearOptions();

        this.showContent();

        var contentArea = $getElement(this.id + '_Content');
        contentArea.className = 'content';

        contentArea.innerHTML = '';

        var tbl = document.createElement("div");
        contentArea.appendChild(tbl);

        var anyShippingMethodValid = false;

        try {
            for (var ctr = 0; ctr < shippingMethods.length; ctr++) {
                var current = shippingMethods[ctr];

                if (current.ForOversizedItem)
                    continue;
                var td = document.createElement("div");

                if (current.IsError) {
                    var lbl = document.createElement("span");
                    lbl.innerHTML = current.Description;
                    td.appendChild(lbl);
                }
                else {
                    var opt = null;
                    opt = document.createElement('input');
                    opt.type = "radio";
                    opt.name = this.id + ":ShippingMethod";
                    if (opt) {
                        opt.id = this.id + "_ShippingMethod_" + ctr;

                        opt.value = current.Code;
                        opt.checked = current.IsDefault;

                        var txt = document.createElement("span");
                        txt.innerHTML = current.Description + ' ' + current.FreightDisplay;

                        td.appendChild(opt);
                        td.appendChild(txt);

                        // register
                        var option = new ise.Controls.ShippingMethodOption(opt, current.Code, current.FreightCalculation, current.Freight);
                        this.registerOption(option);
                    }

                    anyShippingMethodValid = true;
                }
                tbl.appendChild(td);
            }
            //ise.StringResource.getString('showproduct.aspx.33')
            var counter = 0;
            var tblOversized = null;
            var tblBodyOversized = null;

            for (var ctr = 0; ctr < shippingMethods.length; ctr++) {
                var current = shippingMethods[ctr];
                if (!current.ForOversizedItem)
                    continue;

                counter++;
                // initialize headers here
                if (counter == 1) {
                    tbl.appendChild(document.createElement("br"));
                    tblOversized = document.createElement("table");
                    tblOversized.className = "tblShippingMethod";
                    tblBodyOversized = document.createElement("tbody");
                    var rowMessage = document.createElement("tr");
                    var cellMessage = document.createElement("td");
                    cellMessage.colSpan = 3;
                    cellMessage.className = "tdShippingMethodMessage tdShippingMethodLeft";
                    cellMessage.appendChild(document.createTextNode(ise.StringResource.getString('checkoutshipping.aspx.9')));
                    rowMessage.appendChild(cellMessage);
                    tblBodyOversized.appendChild(rowMessage);
                    var row = document.createElement("tr");
                    var cellItemName = document.createElement("td");
                    cellItemName.className = "tdShippingMethodHeader tdShippingMethodLeft";
                    cellItemName.appendChild(document.createTextNode(ise.StringResource.getString('checkoutshipping.aspx.10')));
                    row.appendChild(cellItemName);
                    var cellMethodDesc = document.createElement("td");
                    cellMethodDesc.className = "tdShippingMethodHeader";
                    cellMethodDesc.appendChild(document.createTextNode(ise.StringResource.getString('checkoutshipping.aspx.11')));
                    row.appendChild(cellMethodDesc);
                    var cellFreightDisplay = document.createElement("td");
                    cellFreightDisplay.className = "tdShippingMethodHeader";
                    cellFreightDisplay.appendChild(document.createTextNode(ise.StringResource.getString('checkoutshipping.aspx.12')));
                    row.appendChild(cellFreightDisplay);
                    tblBodyOversized.appendChild(row);
                }

                var row = document.createElement("tr");
                for (var c = 0; c <= 2; c++) {
                    var cell = document.createElement("td");
                    var cellText = null;
                    switch (c) {
                        case 0:
                            cellText = current.OversizedItemName;
                            cell.className = "tdShippingMethodRow tdShippingMethodLeft";
                            break;
                        case 1:
                            cellText = current.Description;
                            cell.className = "tdShippingMethodRow";
                            break;
                        case 2:
                            cellText = current.FreightDisplay;
                            cell.className = "tdShippingMethodRow oversizedFreight";
                            break;
                        default:
                            cellText = "";
                            cell.className = "tdShippingMethodRow";
                    }
                    cell.appendChild(document.createTextNode(cellText));
                    row.appendChild(cell);
                }
                tblBodyOversized.appendChild(row);
            }

            if (tblBodyOversized != null && tblBodyOversized != null) {
                tblOversized.appendChild(tblBodyOversized);
                tbl.appendChild(tblOversized);
            }

        }
        catch (e) {
            alert(e);
            contentArea.innerHTML = e; //'Could not load shipping methods';
        }

        this.showContent();

        if (anyShippingMethodValid) {
            this.onShippingOptionsLoaded();
        }
    },

    showLoading: function () {
        var loadingRow = $getElement(this.id + '_LoadingRow');
        if (null != loadingRow) {
            ise.Utils.showRow(loadingRow);
        }

        var contentRow = $getElement(this.id + '_ContentRow');
        if (null != contentRow) {
            ise.Utils.hideRow(contentRow);
        }
    },

    showContent: function () {
        var loadingRow = $getElement(this.id + '_LoadingRow');
        if (null != loadingRow) {
            ise.Utils.hideRow(loadingRow);
        }

        var contentRow = $getElement(this.id + '_ContentRow');
        if (null != contentRow) {
            ise.Utils.showRow(contentRow);
        }
    },

    onComplete: function (result) {
        alert(result);
    },

    requestShippingMethod: function (addressId) {
        this.showLoading();
        if (addressId != null) {
            this.shippingMethodID = addressId;
        }
        var onCompleteDelegate = Function.createDelegate(this, this.onLoadShippingMethodComplete);
        var service = new ActionService();
        service.ShippingMethod(this.addressValue ? this.addressValue : '', this.id, this.shippingMethodID, onCompleteDelegate);
    },

    getShippingMethod: function () {
        var elemShippingMethod = $getElement(this.id + '_ShippingMethod');
        if (elemShippingMethod) {
            return elemShippingMethod.value;
        }

        return ise.Constants.EMPTY_STRING;
    },

    setFreight: function (value) {
        var elemFreight = $getElement(this.id + '_Freight');
        if (elemFreight) {
            elemFreight.value = value;
        }
    },

    setShippingMethod: function (value) {
        var elemShippingMethod = $getElement(this.id + '_ShippingMethod');
        if (elemShippingMethod) {
            elemShippingMethod.value = value;
        }
    },

    getFreightCalculation: function () {
        var elemFreightCalculation = $getElement(this.id + '_FreightCalculation');
        if (elemFreightCalculation) {
            return elemFreightCalculation.value;
        }

        return ise.Constants.EMPTY_STRING;
    },

    setFreightCalculation: function (value) {
        var elemFreightCalculation = $getElement(this.id + '_FreightCalculation');
        if (elemFreightCalculation) {
            elemFreightCalculation.value = value;
        }
    },

    setValidationSummary: function (summary) {
        this.validationController.setValidationSummary(summary);
    },

    registerValidator: function (validator) {
        this.validationController.register(validator);
    },

    clearValidationSummary: function () {
        this.validationController.clear();
    },

    validate: function (clear) {
        if (this.skipShipping) return true;

        return this.validationController.validate(clear);
    }

}

ise.Controls.ShippingMethodController = {

    initialize : function() {
        this.controls = new Array();
        this.observers = new Array();
    },
    
    registerControl : function(id) {
        var ctrl = new ise.Controls.ShippingMethodControl(id);
        this.controls[id] = ctrl;
        
        this.notifyObservers(ctrl);
        
        return ctrl;
    },
    
    addObserver : function(observer) {
        if(observer) {
            this.observers[this.observers.length] = observer;
        }
    },
    
    notifyObservers : function(control) {
        for(var ctr=0; ctr< this.observers.length; ctr++) {
            this.observers[ctr].notify(control);
        }
    },
    
    getControl : function(id) {
        var ctrl = this.controls[id];
        return ctrl;
    }
    
}

ise.Controls.ShippingMethodController.initialize();